package com.bawei.main

import android.Manifest
import android.app.AlertDialog
import android.content.Intent
import android.content.pm.PackageManager
import android.net.Uri
import android.os.Build
import android.provider.Settings
import android.view.View
import android.webkit.JavascriptInterface
import com.alibaba.android.arouter.facade.annotation.Route
import com.alibaba.android.arouter.launcher.ARouter
import com.bawei.base.RoutePath
import com.bawei.common.base.BaseActivity
import com.bawei.common.dailog.AppUpdateDialog
import com.bawei.main.databinding.ActivityMainBinding
import com.tencent.mmkv.MMKV
import dagger.hilt.android.AndroidEntryPoint

@Route(path = RoutePath.PATH_MAIN_PAGE)
@AndroidEntryPoint
class MainActivity : BaseActivity<ActivityMainBinding>() {

    private lateinit var mAppUpdateDialog: AppUpdateDialog

    private var needUserPermissions = arrayListOf(
        Manifest.permission.READ_EXTERNAL_STORAGE,
        Manifest.permission.WRITE_EXTERNAL_STORAGE,
        Manifest.permission.CAMERA,
        Manifest.permission.READ_PHONE_STATE,
        Manifest.permission.ACCESS_FINE_LOCATION,
        Manifest.permission.ACCESS_COARSE_LOCATION,
        Manifest.permission.RECORD_AUDIO,
    )

    private var unGrantPermissions = arrayListOf<String>()

    private var hasUnGranted = false


    override fun getLayoutId(): Int = R.layout.activity_main

    override fun initViews() {
        appUpdateDialog()
        loadWebView()
    }


    private fun loadWebView(){
        var homeUrl = MMKV.defaultMMKV().decodeString("home_url", "")
        mDataBinding.wbTencent.loadUrl(homeUrl)
        mDataBinding.wbTencent.view.overScrollMode = View.OVER_SCROLL_NEVER
        //添加JS交互
        mDataBinding.wbTencent.addJavascriptInterface(WebViewJsInterface(), "androidinfo") //"androidinfo"是JS中调用时的名称，类似： Window.androidinfo

        //延迟检查用户权限
        mDataBinding.wbTencent.postDelayed({
            autoRequestPermission()
        }, 1000)
    }

    private fun autoRequestPermission(): Boolean {
        //判断是否是Android6.0，动态申请权限
        if (Build.VERSION.SDK_INT >= Build.VERSION_CODES.M){
            //清理历史未授权的权限
            unGrantPermissions.clear()
            //检查用户是否同意过权限
            needUserPermissions.forEach {
                var state = checkSelfPermission(it)
                if (state == PackageManager.PERMISSION_DENIED){
                    unGrantPermissions.add(it)
                }
            }

            //发起用户授权
            if (unGrantPermissions.size > 0){
                requestPermissions(unGrantPermissions.toTypedArray(), 100)
                return false
            }
        }
        return true
    }

    override fun onRequestPermissionsResult(requestCode: Int, permissions: Array<out String>, grantResults: IntArray) {
        super.onRequestPermissionsResult(requestCode, permissions, grantResults)
        //检查是否还存在没有授权的权限
        if (requestCode == 100 && Build.VERSION.SDK_INT >= Build.VERSION_CODES.M){
            unGrantPermissions.forEach {
                if (checkSelfPermission(it) == PackageManager.PERMISSION_DENIED){
                    hasUnGranted = true
                }
            }
        }
        //给出提示，让用户去设置中手动开启权限
        if (hasUnGranted){
            var builder = AlertDialog.Builder(this@MainActivity)
            builder.setTitle("权限提示")
            builder.setMessage("没有授权，请到应用详情中设置")
            builder.setPositiveButton("去设置"){ dialog, _ ->
                dialog.dismiss()
                hasUnGranted = false
                openAppDetailPage()
            }
            builder.setNegativeButton("取消") { dialog, _ ->
                dialog.dismiss()
                hasUnGranted = false
            }

            //弹窗显示
            builder.create().show()
        }
    }

    /**
     * 打开应用详情页面
     */
    private fun openAppDetailPage(){
        var intent = Intent(Settings.ACTION_APPLICATION_DETAILS_SETTINGS)
        intent.data = Uri.fromParts("package", packageName, null)
        this@MainActivity.startActivity(intent)
    }

    /**
     * APP更新
     */
    private fun appUpdateDialog(){
        var hasNewVersion = MMKV.defaultMMKV().decodeBool("has_new_version", true)
        mAppUpdateDialog = AppUpdateDialog(this@MainActivity)
        if (hasNewVersion){
            MMKV.defaultMMKV().encode("has_new_version", false)
            mDataBinding.wbTencent.postDelayed({
                mAppUpdateDialog.show()
            }, 2000)
        }
    }

    /**
     * 跳转到具体的业务模块
     */
    private fun jumpModuleActivity(moduleType: String){
        //1.检查用户权限是否全部同意
        var hasAllPermission = autoRequestPermission()
        if (!hasAllPermission) return

        //2.根据id跳转到具体的业务模块
        when(moduleType){
            "1","2","3","4","5","6" -> ARouter.getInstance().build(RoutePath.PATH_PROPERTY_PAGE).withString("moduleType", moduleType).navigation()
            "7","8","9","10" -> ARouter.getInstance().build(RoutePath.PATH_CULTURE_PAGE).withString("moduleType", moduleType).navigation()
            "11","12" -> ARouter.getInstance().build(RoutePath.PATH_ATTENDANCE_PAGE).withString("moduleType", moduleType).navigation()
            "13","14","15" -> ARouter.getInstance().build(RoutePath.PATH_AUDIT_PAGE).withString("moduleType", moduleType).navigation()
            else -> showToastMsg("敬请期待！！")
        }
    }


    /**
     * 接口方法必须使用@JavascriptInterface来注释
     * 方法名称必须与前端开发人员来统一定义
     */
    inner class WebViewJsInterface{

        @JavascriptInterface
        fun androidparking(id: String) = jumpModuleActivity(id)

        @JavascriptInterface
        fun androidapply(id: String) = jumpModuleActivity(id)

        @JavascriptInterface
        fun androidvisit(id: String) = jumpModuleActivity(id)

        @JavascriptInterface
        fun androidpatrol(id: String) = jumpModuleActivity(id)

        @JavascriptInterface
        fun androidnews(id: String) = jumpModuleActivity(id)
        @JavascriptInterface
        fun androidnoticelist(id: String) = jumpModuleActivity(id)

        @JavascriptInterface
        fun androidrepair(id: String) = jumpModuleActivity(id)

        @JavascriptInterface
        fun androidaddrepair(id: String) = jumpModuleActivity(id)

        @JavascriptInterface
        fun androidaddculture(id: String) = jumpModuleActivity(id)

        @JavascriptInterface
        fun androidaddnotice(id: String) = jumpModuleActivity(id)

        @JavascriptInterface
        fun androidculture(id: String) = jumpModuleActivity(id)

        @JavascriptInterface
        fun androidnotice(id: String) = jumpModuleActivity(id)

        @JavascriptInterface
        fun androidsign(id: String) = jumpModuleActivity(id)

        @JavascriptInterface
        fun androidattendance(id: String) = jumpModuleActivity(id)

        @JavascriptInterface
        fun androidproperty(id: String) = jumpModuleActivity(id)
        @JavascriptInterface
        fun androidcheckculture(id: String) = jumpModuleActivity(id)

        @JavascriptInterface
        fun androidpeople(id: String) = jumpModuleActivity(id)
    }


}
